package hanlp;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLWord;

import java.util.*;

/**
 * @Author hujian
 * @Date 2021/12/15 19:11
 * @Description description
 */
public class ParseUtil {
    public static void main(String[] args) {
        for (Map<String, List<CoNLLWord>> li :
                dict("刘小绪和小明是同学")) {
            System.out.println(li);
        }
    }


    /**
     * @param text 待分析的句子
     * @return 分析结果，按分词结果的顺序组织的
     */
    public static List<CoNLLWord> parser(String text) {

        CoNLLSentence sentence = HanLP.parseDependency(text);

        CoNLLWord[] wordArr = sentence.getWordArray();

        List<CoNLLWord> result = new ArrayList<>();

        Collections.addAll(result, wordArr);

        return result;
    }

    /**
     * 最外层list是为了记录是第几个
     * map中的key记录的是关系
     * map中的list记录的是这个关系的词语
     *
     * @param text 带分析的句子
     * @return 词语依存字典
     */
    public static List<Map<String, List<CoNLLWord>>> dict(String text) {

        CoNLLSentence sentence = HanLP.parseDependency(text);

        //System.out.println(sentence);

        CoNLLWord[] wordArray = sentence.getWordArray();

        List<Map<String, List<CoNLLWord>>> result = new ArrayList<>();

        for (CoNLLWord word : wordArray) {
            HashMap<String, List<CoNLLWord>> map = new HashMap<>();
            for (CoNLLWord child : wordArray) {
                if (word.LEMMA.equals(child.HEAD.LEMMA)) {

                    if (map.containsKey(child.DEPREL)) {
                        map.get(child.DEPREL).add(child);
                    } else {
                        List<CoNLLWord> list = new ArrayList<>();
                        list.add(child);

                        map.put(child.DEPREL, list);
                    }
                }
            }
            result.add(map);
        }
        return result;
    }
}
